package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/Register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Get parameters from user submit.
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String confirm = request.getParameter("confirmPassword");
		java.util.Date utilDate = new java.util.Date();
		Date date = new Date(utilDate.getTime());

		response.getWriter().println(date);
		// Prepare SQL statements.
		String querySQL = "select * from user where UserName = ?";

		// not safe, can be attack by performing injection (fix in the next
		// version)
		String addSQL = "insert into user values('" + username + "', '"
				+ password + "', 'user', '" + date + "')";

		// Prepare connection to the database.
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet resultSet = null;
		if (confirm.equals(password)) {
			try {
				conn = UserManagementDbConnector.getConnection();
				stmt = conn.prepareStatement(querySQL);
				stmt.setString(1, username);
				resultSet = stmt.executeQuery();

				// Account existed.
				if (resultSet.next()) {
					request.setAttribute("msg", "There is an existing account with this username!");
					request.getRequestDispatcher("Register.jsp").forward(
							request, response);
				} else {

					// Add new user to the database.
					stmt = conn.prepareStatement(addSQL);
					stmt.executeUpdate(addSQL);

					// Save the newly registered user to session.
					request.getSession().setAttribute("username", username);
					request.getSession().setAttribute("password", password);
					// request.setAttribute("message",
					// "You have successfully registered a new account!");
					request.getRequestDispatcher("RegisterSuccess.jsp").forward(request, response);

					resultSet.close();
					stmt.close();
					conn.close();
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}
		} else {
			request.setAttribute("msg", "Password and Confirm Password are mismatch! Please try again.");
			request.getRequestDispatcher("Register.jsp").forward(request, response);
		}
	}

}
